import { _decorator, Component, Node, Vec2, v2, Material, Sprite, Skeleton, sp } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ColorAdjustBase')
export class ColorAdjustBase extends Component {
    private static m_Adjuster: ColorAdjustBase[] = [];
    public static get adjuster() {
        return this.m_Adjuster;
    }

    @property({ displayName: "亮度" })
    private m_Brightness: Vec2 = v2();
    @property({ displayName: "饱和度" })
    private m_Saturation: Vec2 = v2();
    @property({ displayName: "对比度" })
    private m_Contrast: Vec2 = v2();
    @property({ displayName: "速度" })
    private m_Speed: number = 0;

    private m_Material: Material;
    private m_Spine: sp.Skeleton;

    onEnable() {
        const sprite = this.node.getComponent(Sprite);
        if (sprite) {
            this.m_Spine = null;
            this.m_Material = sprite.customMaterial;
        } else {
            this.m_Spine = this.node.getComponent(sp.Skeleton);
            this.m_Material = this.m_Spine.customMaterial;
        }
        ColorAdjustBase.m_Adjuster.push(this);
    }

    onDisable() {
        this.m_Material = null;
        const adjuster = ColorAdjustBase.m_Adjuster;
        adjuster.splice(adjuster.indexOf(this), 1);
    }

    private lerp(a: number, b: number, r: number) {
        return a + (b - a) * r;
    }

    updateTimer(ratio: number) {
        let material = this.m_Material;
        material.setProperty("brightness", this.lerp(this.m_Brightness.x, this.m_Brightness.y, ratio));
        material.setProperty("saturation", this.lerp(this.m_Saturation.x, this.m_Saturation.y, ratio));
        material.setProperty("contrast", this.lerp(this.m_Contrast.x, this.m_Contrast.y, ratio));

        if (material.getProperty("uvMove")) {
            material.setProperty("uvMove", this.m_Speed);
        }

        this.m_Spine && (this.m_Spine.customMaterial = material);
    }
}

